package com.victor.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;

@Slf4j
public class Base64ToPdfUtil {

    public static boolean base64ToPdf(String base64Str, String outputFilepath) {

        if (base64Str.startsWith("data:application/pdf;base64,")) {
            String base64 = base64Str.replace("data:application/pdf;base64,", "");

            // 解码Base64字符串
            byte[] decodedBytes = Base64.getDecoder().decode(base64);

            try {
                // 将解码后的字节写入PDF文件
                Files.write(Paths.get(outputFilepath), decodedBytes);
                return true;
            } catch (Exception e) {
               log.error("base64ToPdf error", e);
               throw new RuntimeException("生成pdf 失败");
            }
        }

        return false;
    }

    public static boolean pdfInfosToPdf(List<String> pdfInfos, String outputFilepath) {

        try {
            // 创建PDF合并工具
            PDFMergerUtility pdfMerger = new PDFMergerUtility();
            ByteArrayOutputStream mergedPdfOutputStream = new ByteArrayOutputStream();

            // 临时存储解码后的PDF文档
            for (String base64Pdf : pdfInfos) {
                int startIndex = base64Pdf.indexOf(",") + 1;
                String base64Data = base64Pdf.substring(startIndex);
                byte[] pdfBytes = Base64.getDecoder().decode(base64Data);
                PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfBytes));
                pdfMerger.addSource(new ByteArrayInputStream(pdfBytes));
                document.close();
            }

            // 设置输出流
            pdfMerger.setDestinationStream(mergedPdfOutputStream);
            // 合并PDF
            pdfMerger.mergeDocuments(null);


            // 将解码后的字节写入PDF文件
            Files.write(Paths.get(outputFilepath), mergedPdfOutputStream.toByteArray());
            return true;
        } catch (IOException e) {
            log.error("base64ToPdf error", e);
            throw new RuntimeException("生成pdf失败!");
        }

    }
}
